# -*-encoding: utf-8 -*-

from pyramid.view import view_config
from pyramid.view import view_defaults
from pyramid.response import Response
from pyramid.httpexceptions import HTTPFound
import json
from ..utils.Hash.HashUtil import HashUtil
from ..utils.Image.ImageUtil import ImageUtil
from ..utils.DB import MySqlCRUD
import time, os, uuid, shutil, hashlib
import base64
from ..utils.Queue import UploadTasks
from ..utils.SMS import MobSMS
from ..utils.Cache.TokenCache import TokenCache
from ..utils.Cache.ChecksumCache import ChecksumCache
import logging

import sys
reload(sys)
sys.setdefaultencoding('utf-8')
log = logging.getLogger(__name__)

class Base(object):
    def __init__(self, request):
        self.request = request

    def checkEmailAvailable(self, email):
        sql = "select email from user_info where email = %s"
        result = MySqlCRUD.selectImpl(sql, email)
        log.debug(result)
        if result:
            return False
        else:
            return True

    def checkTelAvailable(self, tel):
        sql = "select tel from user_info where tel = %s"
        result = MySqlCRUD.selectImpl(sql, tel)
        log.debug(result)
        if result:
            return False
        else:
            return True

    def fetchEmailRegistration(self, email):
        log.debug('fetch Email:' + email)
        #print base64.b64encode(self.__getCurrentTimeString())
        #print base64.b64decode(base64.b64encode(self.__getCurrentTimeString()))

    def fetchTelRegistration(self, tel):
        log.debug('fetch tel:' + tel)

    def calcSmsCheckSum(self, telnum, csum):
        #APP_ID
        mobsms = MobSMS.MobSMS()
        log.debug('[REGISTER]tel:' + str(telnum) + ',checknum:' + csum)
        responseCode = mobsms.verify_sms_code(86, telnum, csum)
        log.debug('calculate the checksum finished!!')
        log.debug(responseCode)
        return responseCode

    def getCurrentTimeString(self):
        #print time.time() + 30 * 60
        timeString = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time() + 30 * 60))
        #turn Formated time String to time(s)
        #print time.mktime(time.strptime(timeString,'%Y-%m-%d %H:%M:%S'))
        return timeString

    def calculateToken(self, tString, tel):
        tmpEString = HashUtil.getStringMD5(tel + tString)
        tmpTokenString = base64.b64encode(tString + tmpEString)
        return tmpTokenString
